package com.tangtang.transactional.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.tangtang.transactional.domain.Order;
import com.tangtang.transactional.domain.OrderLine;
import com.tangtang.transactional.mapper.OrderLineMapper;
import com.tangtang.transactional.mapper.OrderMapper;
import com.tangtang.transactional.service.OrderLineService;
import com.tangtang.transactional.service.OrderService;
import com.tangtang.transactional.vo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderLineService orderLineService;

    //    @Transactional(rollbackFor = Exception.class, propagation = Propagation.MANDATORY)
    @Override
    public boolean insert(Order order) {
        return orderMapper.insert(order);
    }

//    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addOrder(@RequestBody List<ProductVO> products) {
        Order order = new Order();
        order.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        order.setId(snowflake.nextId());
        List<OrderLine> orderLines = products.stream().map(productVO -> {
            OrderLine orderLine = new OrderLine();
            BigDecimal priceAmount = productVO.getPrice().multiply(productVO.getQuantity());
            order.setTotalAmount(order.getTotalAmount().add(priceAmount));
            BigDecimal taxAmount = productVO.getTax().multiply(productVO.getQuantity());
            order.setTaxAmount(order.getTaxAmount().add(taxAmount));

            BeanUtil.copyProperties(productVO, orderLine);
            orderLine.setId(snowflake.nextId());
            orderLine.setOrderId(order.getId());
            orderLine.setAmount(priceAmount.add(taxAmount));
            return orderLine;
        }).collect(Collectors.toList());

        this.insert(order);

        for (int i = 0; i < orderLines.size(); i++) {
            orderLineService.insert(orderLines.get(i));
//            if(i==2){
//                int a = 0 / 0;
//            }
        }
        return true;
    }
}
